<template>
  <div class="contentBox setScrollbar">
    <div class="btnBox">
      <el-button
        type="primary"
        @click="addDept"
      >
        新增部门
      </el-button>
    </div>
    <div class="content">
      <drag-line hidden_auto="auto">
        <div slot="left" class="leftTree setScrollbar">
          <el-tree
            :data="treeData"
            :props="defaultProps"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <span
              slot-scope="{ node }"
              class="span-ellipsis"
            >
              <span :title="node.label">{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
        <div slot="right">
          <template>
            <el-table
              v-loading="loading"
              :data="tableData"
              stripe
              style="width: 100%"
            >
              <el-table-column
                type="index"
                label="序号"
                width="50"
                align="center"
              />
              <el-table-column
                prop="fullName"
                label="部门名称"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <span
                    class="tabDetail"
                    @click="handleDetail(scope.row)"
                  >{{ scope.row.fullName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="simpleName"
                label="部门简称"
                width="180"
                align="center"
              />
              <el-table-column
                prop="description"
                label="部门简介"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                prop="pname"
                label="上级部门"
                width="180"
                align="center"
              />
              <el-table-column
                prop="date"
                label="操作"
                width="280"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    class="MR18 bg5584FF"
                    type="primary"
                    @click="editDept(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="mini"
                    class="MR18 bg5584FF"
                    type="primary"
                    @click="deleteDept(scope.row.deptId)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <div class="pageBox">
            <el-pagination
              background
              :current-page.sync="currentPage"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </drag-line>
    </div>
    <!-- 新增部门 -->
    <el-dialog
      title="新增部门"
      :visible.sync="addDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="addHandleClose"
    >
      <el-form
        ref="ruleForm"
        v-loading="addLoading"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 half"
      >
        <el-form-item
          label="部门名称"
          prop="fullName"
          style="width:45%"
        >
          <el-input
            v-model.trim="ruleForm.fullName"
            placeholder="请输入"
            maxlength="200"
          />
        </el-form-item>
        <el-form-item
          label="部门简称"
          style="width:45%"
        >
          <el-input
            v-model.trim="ruleForm.simpleName"
            placeholder="请输入"
            maxlength="45"
          />
        </el-form-item>
        <el-form-item
          label="上级部门"
          style="width:45%"
        >
          <el-cascader
            v-model="ruleForm.deptId"
            :options="treeData"
            :props="deptDeftProps"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item
          label="部门简介"
          style="width:100%"
        >
          <el-input
            v-model.trim="ruleForm.description"
            type="textarea"
            maxlength="500"
          />
        </el-form-item>
        <el-form-item style="width:100%;">
          <div class="formBtnBox">
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              提交
            </el-button>
            <el-button @click="addDialogVisible = false">
              取消
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑部门 -->
    <el-dialog
      title="编辑部门"
      :visible.sync="editDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      @closed="editHandleClose"
    >
      <el-form
        ref="editruleForm"
        v-loading="editLoading"
        :model="editRuleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm paddLr20 textarea200 half"
      >
        <el-form-item
          label="部门名称"
          prop="fullName"
          style="width:45%"
        >
          <el-input
            v-model.trim="editRuleForm.fullName"
            maxlength="200"
          />
        </el-form-item>
        <el-form-item
          label="部门简称"
          style="width:45%"
        >
          <el-input
            v-model.trim="editRuleForm.simpleName"
            placeholder="请输入"
            maxlength="45"
          />
        </el-form-item>
        <el-form-item
          label="上级部门"
          style="width:45%"
        >
          <el-cascader
            v-model="editRuleForm.pDept"
            :options="treeData"
            :props="editDeptDeftProps"
            disabled
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item
          label="部门简介"
          style="width:100%"
        >
          <el-input
            v-model.trim="editRuleForm.description"
            type="textarea"
            maxlength="500"
          />
        </el-form-item>
        <el-form-item style="width:100%;">
          <div class="formBtnBox">
            <el-button
              type="primary"
              @click="editSubmitForm('editruleForm')"
            >
              提交
            </el-button>
            <el-button @click="editDialogVisible = false">
              取消
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="删除部门"
      :visible.sync="delDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <p>确认要删除该部门？此操作不可逆</p>
      <div class="formBtnBox">
        <el-button
          type="primary"
          @click="sureDelete"
        >
          确定
        </el-button>
        <el-button @click="delDialogVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { Message } from 'element-ui';
import { getDeptPreVal } from '@/utils';
import dragLine from '@/components/draggle_line';
export default {
  components: { dragLine },
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      delDialogVisible: false,
      loading: false,
      addLoading: false,
      editLoading: false,
      currentPage: 1,
      total: 0,
      current: 1,
      delDeptId: '',
      ruleForm: {},
      editRuleForm: {},
      rules: {
        fullName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ]
      },
      searchObj: {
        deptId: ''
      },
      treeData: [],
      tableData: [],
      seleListData: [],
      filterSeleListData: [],
      defaultProps: {
        children: 'nodes',
        label: 'text'
      },
      deptDeftProps: {
        children: 'nodes',
        expandTrigger: 'hover',
        emitPath: false,
        label: 'text',
        value: 'deptId',
        checkStrictly: true
      },
      editDeptDeftProps: {
        children: 'nodes',
        expandTrigger: 'hover',
        emitPath: false,
        label: 'text',
        value: 'text',
        checkStrictly: true
      }
    };
  },
  created() {
    this.getTabTada({ current: 1, limit: 10 });
    this.getDeptTree();
    this.getseleListData();
  },
  methods: {
    getTabTada(searchObj, pageObj) {
      this.loading = true;
      const pms = Object.assign(searchObj, pageObj);
      this.$axios
        .get('/dept/list', { params: pms })
        .then(res => {
          this.tableData = res.data.records;
          this.loading = false;
          this.total = res.data.total;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getDeptTree() {
      this.$axios.get('/dept/treeview').then(res => {
        this.treeData = res.data;
      });
    },
    getseleListData() {
      this.$axios.get('/dept/pDept').then(res => {
        this.seleListData = res.data;
      });
    },
    handleNodeClick(data) {
      // 树节点点击方法
      this.$set(this.searchObj, 'deptId', data.deptId);
      this.getTabTada(this.searchObj, { current: this.current, limit: 10 });
    },
    addDept() {
      //   this.$router.push({ name: "Discussadd" });
      this.addDialogVisible = true;
      this.getTabTada({ current: this.current, limit: 10 });
    },
    handleChange(value) {
      console.log(value, this.treeData);
    },
    submitForm(formName) {
      // 表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          let queryParams = {};
          if (this.ruleForm.deptId) {
            queryParams = {
              'sys_dept:data[]': {
                '@column': '*',
                '@where': {
                  'pid@eq': this.ruleForm.deptId,
                  'full_name@eq': this.ruleForm.fullName
                }
              }
            };
          } else {
            queryParams = {
              'sys_dept:data[]': {
                '@column': '*',
                '@where': {
                  'pid@eq': 0,
                  'full_name@eq': this.ruleForm.fullName
                }
              }
            };
          }
          this.COM.jsonsqlForSelect(queryParams).then(res => {
            if (res.data.length > 0) {
              Message.warning(
                '当前部门已存在于所选上级部门，请修改部门名称后再次新增'
              );
            } else {
              if (this.ruleForm.deptId) {
                this.ruleForm.pDept = getDeptPreVal(
                  this.ruleForm.deptId,
                  this.treeData
                );
              }
              this.add();
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    add() {
      delete this.ruleForm.deptId;
      this.addLoading = true;
      this.$axios
        .post('/dept/add', this.ruleForm)
        .then(res => {
          if (res.code == 200) {
            Message.success('新增成功');
            this.getTabTada(this.searchObj, {
              current: this.current,
              limit: 10
            });
            this.getDeptTree();
            this.ruleForm.pDept = '';
            this.addDialogVisible = false;
            this.addLoading = false;
          } else {
            Message.error(res.message);
            this.addLoading = false;
            this.ruleForm.pDept = '';
          }
        })
        .catch(() => {
          this.addLoading = false;
          this.ruleForm.pDept = '';
        });
    },
    editDept(row) {
      console.log(row);
      let list = JSON.parse(JSON.stringify(this.treeData));
      this.filterSeleListData = list.filter(item => item.deptId !== row.deptId);
      this.editRuleForm = JSON.parse(JSON.stringify(row));
      this.editDialogVisible = true;
    },
    editSubmitForm(formName) {
      // 表单提交
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.editRuleForm);
          let queryParams = {
            'sys_dept:data{}': {
              '@column': '*',
              '@where': {
                'pid@eq': this.editRuleForm.pid,
                'full_name@eq': this.editRuleForm.fullName
              }
            }
          };
          this.COM.jsonsqlForSelect(queryParams).then(res => {
            // 判断返回数据是否是提交的数据
            if (
              res.data.length == 0 ||
              this.editRuleForm.deptId === res.data.dept_id
            ) {
              this.edit();
            } else {
              Message.warning(
                '当前部门已存在于所选上级部门，请修改部门名称后再次新增'
              );
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    edit() {
      this.editLoading = true;
      this.$axios
        .post('/dept/update', this.editRuleForm)
        .then(res => {
          if (res.code == 200) {
            Message.success('编辑成功');
            this.getTabTada(this.searchObj, {
              current: this.current,
              limit: 10
            });
            this.getDeptTree();
            this.editDialogVisible = false;
            this.editLoading = false;
          } else {
            Message.error(res.message);
            this.editLoading = false;
          }
        })
        .catch(() => {
          this.editLoading = false;
        });
    },
    deleteDept(id) {
      const queryParams = {
        'sys_dept:data[]': {
          '@column': '*',
          '@where': {
            'pids@like': `%${id}%`
          }
        }
      };
      this.COM.jsonsqlForSelect(queryParams).then(res => {
        console.log(res);
        if (res.data.length > 0) {
          Message.warning('当前部门存在子部门，不能删除');
        } else {
          const queryParams = {
            'sys_user:data[]': {
              '@column': '*',
              '@where': {
                'dept_id@eq': id,
                'status@notEq': 'DELETED'
              }
            }
          };
          this.COM.jsonsqlForSelect(queryParams).then(res => {
            if (res.data.length > 0) {
              Message.warning('当前部门存在绑定用户，不能删除');
            } else {
              this.delDeptId = id;
              this.delDialogVisible = true;
            }
          });
        }
      });
    },
    sureDelete() {
      this.$axios
        .get(`/dept/delete?deptId=${this.delDeptId}`)
        .then(res => {
          if (res.data.code == 200) {
            Message.success('已删除');
            this.getTabTada(this.searchObj, {
              current: this.current,
              limit: 10
            });
            this.getDeptTree();
            this.delDialogVisible = false;
            // this.editLoading = false;
          } else {
            Message.error(res.data.message);
          }
        })
        .catch(() => {
          this.editLoading = false;
          Message.error('删除失败');
        });
    },
    handleDetail(row) {
      //   this.$router.push({ name: "Discussdetail", query: { id: row.id } });
    },
    handleCurrentChange(val) {
      // 分页跳转
      this.current = val;
      this.getTabTada(this.searchObj, { current: val, limit: 10 });
    },
    addHandleClose() {
      this.$refs.ruleForm.resetFields();
      this.ruleForm = {};
    },
    editHandleClose() {}
  }
};
</script>
<style lang="scss" scoped>
  .page_container {
    width: 100%;
    height: 100%;
    display: flex;
    .line {
      height: 100%;
      width: 4px;
      border-left: 1px solid rgba(0, 0, 0, 0.1);
      cursor: w-resize;
    }
  }
</style>
